package question.solution8;

import question.SolutionTemplate;

public class Solution8 implements SolutionTemplate {

    public int myAtoi(String s) {
        String noBlankString = s.trim();
        if(noBlankString.length() == 0){
            return 0;
        }
        boolean negative = false;
        if(noBlankString.charAt(0) == '-'){
            negative = true;
        }
        String numberPart = "";
        if(negative || noBlankString.charAt(0) == '+'){
            numberPart = noBlankString.substring(1);
        }else{
            numberPart = noBlankString;
        }
        int sum = 0;
        int warnNumber = Integer.MAX_VALUE/10;

        for(int i=0;i<numberPart.length();i++){
            if(numberPart.charAt(i)<'0' || numberPart.charAt(i)>'9'){
                break;
            }
            if(sum>warnNumber){
                return negative?Integer.MIN_VALUE:Integer.MAX_VALUE;
            }
            int currentDigit = numberPart.charAt(i)-48;
            if(sum==warnNumber){
                if(currentDigit > 8){
                    return negative?Integer.MIN_VALUE:Integer.MAX_VALUE;
                }else if(currentDigit == 8){
                    if(!negative){
                        return Integer.MAX_VALUE;
                    }
                }
            }
            sum*=10;
            sum += currentDigit;
        }

        return negative ? -sum : sum;
    }

    @Override
    public void test() {

        System.out.println(myAtoi("-91283472332"));
    }

}
